package es

import (
	"bytes"
	"context"
	"course_srv/course"
	"course_srv/models/mysql"
	"encoding/json"
	"fmt"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"log"
	"strconv"
)

func SyncCourse(course mysql.Course) {

	data, err := json.Marshal(course)
	if err != nil {
		log.Fatalf("Error marshaling document: %s", err)
	}

	// Set up the request object.
	req := esapi.IndexRequest{
		Index:      "course",
		DocumentID: strconv.Itoa(int(course.ID)),
		Body:       bytes.NewReader(data),
		Refresh:    "true",
	}

	// Perform the request with the client.
	res, err := req.Do(context.Background(), EsClient)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()
}

func EsList(keyword string) (esList []*course.CourseList) {
	query := map[string]interface{}{}
	if keyword == "" {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match_all": map[string]interface{}{},
			},
		}
	} else {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{
					"Name": keyword,
				},
			},
		}
	}
	sortQuery := []map[string]interface{}{
		{
			"Price": map[string]interface{}{
				"order": "desc",
			},
		},
	}
	query["sort"] = sortQuery

	var buf bytes.Buffer
	json.NewEncoder(&buf).Encode(query)
	es := EsClient
	res, err := es.Search(
		es.Search.WithContext(context.Background()),
		es.Search.WithIndex("course"),
		es.Search.WithBody(&buf),
		es.Search.WithTrackTotalHits(true),
		es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()
	fmt.Println(res.Body)
	r := map[string]interface{}{}
	json.NewDecoder(res.Body).Decode(&r)
	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		resp := hit.(map[string]interface{})["_source"].(map[string]interface{})
		esList = append(esList, &course.CourseList{
			Id:      int32(resp["ID"].(float64)),
			Name:    resp["Name"].(string),
			Teacher: resp["Teacher"].(string),
			Intro:   resp["Intro"].(string),
			Price:   float32(resp["Price"].(float64)),
			Cover:   resp["Cover"].(string),
			Video:   resp["Video"].(string),
		})
	}

	return esList
}
